Chapter 15: Defining Our Routes

After the navbar section in App.js, add the route section by adding the below codes in bold:

Modify Bold Code

return (

<div className="App">

<Navbar bg="primary" variant="dark">

...

</Navbar>

<div className="container mt-4">

<Switch>

<Route exact path={["/", "/todos"]} render={(props) =>

<TodosList {...props} token={token} />

}>

</Route>

<Route path="/todos/create" render={(props)=>

<AddTodo {...props} token={token} />

}>

</Route>

<Route path="/todos/:id/" render={(props)=>

<AddTodo {...props} token={token} />

}>

</Route>

<Route path="/login" render={(props)=>

<Login {...props} login={login} />

}>

</Route>

<Route path="/signup" render={(props)=>

<Signup {...props} signup={signup} />

}>

</Route>

</Switch>

</div>

</div>

Code Explanation

We use a Switch component to switch between different routes. The Switch component renders the first route that

matches.

Analyze Code

<Route exact path={["/", "/todos"]} render={(props) =>

<TodosList {...props} token={token} />

}>

</Route>

We first have the exact path route. If the path is “/” or “/todos”, show the TodosList component. We use render to

allows us to pass data into a component by passing in an object called props. Specifically, we pass in the token for

the user to authenticate itself with the backend API. We will see later how props work when we implement the

AddTodo component.

Analyze Code

<Route path="/todos/create" render={(props)=>

<AddTodo {...props} token={token} />

}>

</Route>

We next have the route for "/todos/create" to render the AddTodo component. We pass in token because only

authenticated users can create todos.

Analyze Code

<Route path="/todos/:id/" render={(props)=>

<AddTodo {...props} token={token} />

}>

</Route>

We then have the route for "/todos/:id/" which also renders the AddTodo component but this time, it’s to update the

todo item. Again, we pass in token because only authenticated users can update todos.

We next have the routes for "/login" and “/signup” to render the Login and Signup component respectively. We do